<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="70%"
    title="修改"
    :dialog-style="{ top: '20px' }"
  >
    <div v-if="visible" v-permission="['base-data:make:modify']" v-loading="loading">
      <a-form ref="form" :model="formData" :rules="rules">
        <a-form-item label="制作名称" name="name">
          <a-input v-model:value="formData.name" max-length="255" allow-clear />
        </a-form-item>
        <a-form-item label="制作描述" name="description">
          <a-textarea v-model:value="formData.description" max-length="65,535" allow-clear />
        </a-form-item>
        <a-form-item label="状态" name="available">
          <a-select v-model:value="formData.available" allow-clear>
            <a-select-option
              v-for="item in $enums.AVAILABLE.values()"
              :key="item.code"
              :value="item.code"
            >
              {{ item.desc }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <vxe-grid
            resizable
            show-overflow
            :show-footer="true"
            highlight-hover-row
            keep-source
            row-id="id"
            :expand-config="{ expandAll: true }"
            :columns="materialTableColumn"
            :toolbar-config="toolbarConfig"
            :data="formData.materials"
            :footer-data="footerData"
            :height="450"
            :scroll-y="{
              enabled: true,
              gt: 0,
            }"
          >
            <!-- 工具栏 -->
            <template #toolbar_buttons>
              <a-space>
                <a-button type="primary" @click="addMaterial">添加主材料</a-button>
              </a-space>
            </template>
            <!-- 原料名称 -->
            <template #productName_default="{ rowIndex, row }">
              <a-form-item :name="['materials', rowIndex, 'productId']" no-style required>
                <product-selector
                  v-model:value="row.productId"
                  :request-params="{
                    productType: [1, 4].join(','),
                  }"
                  @input-row="
                    (data) => {
                      row.code = data?.code;
                      row.skuCode = data?.skuCode;
                      row.spec = data?.spec;
                      row.consumeUnitId = data?.unit;
                      row.consumeNum = null;
                      row.consumeCost = null;
                      calcCost(row);
                    }
                  "
                  @load-complete="
                    (data) => {
                      $nextTick(() => {
                        row.code = data[0]?.code;
                        row.skuCode = data[0]?.skuCode;
                        row.spec = data[0]?.spec;
                        calcCost(row);
                      });
                    }
                  "
                />
              </a-form-item>
            </template>
            <!-- 消耗单位 -->
            <template #consumeUnit_default="{ rowIndex, row }">
              <a-form-item :name="['materials', rowIndex, 'consumeUnitId']" no-style required>
                <product-unit-select
                  v-model:value="row.consumeUnitId"
                  :product-id="row.productId"
                  :disabled="!!!row.productId"
                  @change="calcCost(row)"
                />
              </a-form-item>
            </template>
            <!-- 消耗数量 -->
            <template #consumeNum_default="{ rowIndex, row }">
              <a-form-item :name="['materials', rowIndex, 'consumeNum']" no-style required>
                <a-input-number
                  v-model:value="row.consumeNum"
                  min="0"
                  :precision="4"
                  :disabled="!!!row.productId"
                  @change="calcCost(row)"
                />
              </a-form-item>
            </template>
            <!-- 消耗成本 -->
            <template #consumeCost_default="{ rowIndex, row }">
              <a-form-item :name="['materials', rowIndex, 'consumeCost']" no-style required>
                <a-input-group compact>
                  <a-input-number
                    style="width: calc(100% - 50px)"
                    v-model:value="row.consumeCost"
                    min="0"
                    :precision="6"
                    :disabled="!!!row.productId"
                  />
                  <a-button type="primary" :disabled="!!!row.productId" @click="calcCost(row)">
                    计算
                  </a-button>
                </a-input-group>
              </a-form-item>
            </template>
            <!-- 操作 -->
            <template #action_default="{ rowIndex }">
              <a-space>
                <a-button type="link" @click="() => formData.materials.splice(rowIndex, 1)" danger>
                  删除
                </a-button>
              </a-space>
            </template>

            <!-- 替代品 -->
            <template #replacements_default="{ rowIndex, row }">
              <a-card>
                <vxe-grid
                  resizable
                  show-overflow
                  highlight-hover-row
                  keep-source
                  row-id="id"
                  :expand-config="{ expandAll: true }"
                  :columns="materialTableColumn.filter((item) => item.type !== 'expand')"
                  :toolbar-config="toolbarConfig"
                  :data="row.replacements"
                  :height="200"
                >
                  <!-- 工具栏 -->
                  <template #toolbar_buttons>
                    <a-space>
                      <a-button type="primary" @click="addReplacement(rowIndex)">
                        添加替代材料
                      </a-button>
                    </a-space>
                  </template>
                  <!-- 原料名称 -->
                  <template #productName_default="data">
                    <a-form-item
                      :name="['materials', rowIndex, 'replacements', data.rowIndex, 'productId']"
                      no-style
                      required
                    >
                      <product-selector
                        v-model:value="data.row.productId"
                        :request-params="{
                          productType: [1, 4].join(','),
                        }"
                        @input-row="
                          (rowData) => {
                            data.row.code = rowData?.code;
                            data.row.skuCode = rowData?.skuCode;
                            data.row.spec = rowData?.spec;
                            data.row.consumeUnitId = rowData?.unit;
                            data.row.consumeNum = null;
                            data.row.consumeCost = null;
                            calcCost(row);
                          }
                        "
                        @load-complete="
                          (rowData) => {
                            $nextTick(() => {
                              data.row.code = rowData[0]?.code;
                            });
                          }
                        "
                      />
                    </a-form-item>
                  </template>
                  <!-- 消耗单位 -->
                  <template #consumeUnit_default="data">
                    <a-form-item
                      :name="[
                        'materials',
                        rowIndex,
                        'replacements',
                        data.rowIndex,
                        'consumeUnitId',
                      ]"
                      no-style
                      required
                    >
                      <product-unit-select
                        v-model:value="data.row.consumeUnitId"
                        :product-id="data.row.productId"
                        :disabled="!!!data.row.productId"
                        @change="calcCost(data.row)"
                      />
                    </a-form-item>
                  </template>
                  <!-- 消耗数量 -->
                  <template #consumeNum_default="data">
                    <a-form-item
                      :name="['materials', rowIndex, 'replacements', data.rowIndex, 'consumeNum']"
                      no-style
                      required
                    >
                      <a-input-number
                        v-model:value="data.row.consumeNum"
                        min="0"
                        :precision="4"
                        :disabled="!!!data.row.productId"
                        @change="calcCost(data.row)"
                      />
                    </a-form-item>
                  </template>
                  <!-- 消耗成本 -->
                  <template #consumeCost_default="data">
                    <a-form-item
                      :name="['materials', rowIndex, 'replacements', data.rowIndex, 'consumeNum']"
                      no-style
                      required
                    >
                      <a-input-group compact>
                        <a-input-number
                          style="width: calc(100% - 50px)"
                          v-model:value="data.row.consumeCost"
                          min="0"
                          :precision="6"
                          :disabled="!!!row.productId"
                        />
                        <a-button
                          type="primary"
                          :disabled="!!!data.row.productId"
                          @click="calcCost(data.row)"
                        >
                          计算
                        </a-button>
                      </a-input-group>
                    </a-form-item>
                  </template>
                  <!-- 操作 -->
                  <template #action_default="data">
                    <a-space>
                      <a-button
                        type="link"
                        @click="
                          () => formData.materials[rowIndex].replacements.splice(data.rowIndex, 1)
                        "
                        danger
                      >
                        删除
                      </a-button>
                    </a-space>
                  </template>
                </vxe-grid>
              </a-card>
            </template>
          </vxe-grid>
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <div class="form-modal-footer">
        <a-space>
          <a-button type="primary" :loading="loading" html-type="submit" @click="submit">
            保存
          </a-button>
          <a-button :loading="loading" @click="closeDialog">取消</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/base-data/make';
  import * as productApi from '@/api/base-data/product/info';
  import ProductSelector from '@/components/Selector/src/ProductSelector.vue';
  import ProductUnitSelect from '@/views/base-data/unit/product-unit-select/index.vue';

  export default defineComponent({
    // 使用组件
    components: { ProductUnitSelect, ProductSelector },
    props: {
      id: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        // 是否可见
        visible: false,
        // 是否显示加载框
        loading: false,
        // 表单数据
        formData: {},
        // 表单校验规则
        rules: {
          name: [{ required: true, message: '请输入制作名称' }],
        },
        //
        materialTableColumn: [
          {
            title: '替代',
            type: 'expand',
            field: 'expand',
            width: 80,
            align: 'center',
            slots: { content: 'replacements_default' },
          },
          {
            field: 'type',
            title: '类别',
            width: 80,
            formatter: ({ cellValue }) => (cellValue === 0 ? '主材料' : '替代材料'),
          },
          {
            field: 'productName',
            title: '原料名称',
            minWidth: 160,
            slots: { default: 'productName_default' },
          },
          { field: 'code', title: '原料编码', width: 100 },
          { field: 'skuCode', title: '原料SKU', width: 100 },
          { field: 'spec', title: '原料规格', minWidth: 120 },
          {
            field: 'consumeUnitId',
            title: '消耗单位',
            width: 100,
            slots: { default: 'consumeUnit_default' },
          },
          {
            field: 'consumeNum',
            title: '消耗数量',
            width: 120,
            slots: { default: 'consumeNum_default' },
          },
          {
            field: 'consumeCost',
            title: '成本价',
            minWidth: 140,
            slots: { default: 'consumeCost_default' },
          },
          { title: '操作', width: 80, fixed: 'right', slots: { default: 'action_default' } },
        ],
        toolbarConfig: {
          zoom: false,
          refresh: false,
          custom: false,
          // 自定义左侧工具栏
          slots: {
            buttons: 'toolbar_buttons',
          },
        },
        footerData: [
          {
            expand: '合计',
            type: '-',
            productName: '',
            code: '',
            skuCode: '',
            spec: '',
            consumeUnitId: '',
            consumeNum: 0,
            consumeCost: 0,
          },
        ],
      };
    },
    watch: {
      'formData.materials': {
        handler() {
          this.calcSum();
        },
        deep: true,
      },
    },
    created() {
      this.initFormData();
    },
    methods: {
      // 打开对话框 由父页面触发
      openDialog() {
        this.visible = true;

        this.$nextTick(() => this.open());
      },
      // 关闭对话框
      closeDialog() {
        this.visible = false;
        this.$emit('close');
      },
      // 初始化表单数据
      initFormData() {
        this.formData = {
          name: '',
          description: '',
          materials: [],
        };
        this.calcSum();
      },
      // 提交表单事件
      submit() {
        this.$refs.form.validate().then((valid) => {
          if (valid) {
            this.loading = true;
            api
              .update(this.formData)
              .then(() => {
                this.$msg.createSuccess('修改成功！');
                this.$emit('confirm');
                this.visible = false;
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      // 页面显示时触发
      open() {
        // 初始化数据
        this.initFormData();

        // 查询数据
        this.loadFormData();
      },
      // 查询数据
      loadFormData() {
        this.loading = true;
        api
          .get(this.id)
          .then((data) => {
            this.formData = data;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 添加主材料
      addMaterial() {
        this.formData.materials.push({
          type: 0,
          productId: '',
          replacements: [],
        });
      },
      // 添加辅助材料
      addReplacement(rowIndex) {
        this.formData.materials[rowIndex].replacements.push({
          type: 1,
          productId: '',
        });
      },
      // 计算用量成本
      calcCost(row) {
        if (row && row.productId && row.consumeUnitId && row.consumeNum) {
          productApi
            .calcCost({
              productId: row.productId,
              unitId: row.consumeUnitId,
              num: row.consumeNum,
            })
            .then((res) => {
              row.consumeCost = res;
            });
        }
      },
      calcSum() {
        this.footerData[0].productName = this.formData.materials.length;
        this.footerData[0].consumeNum = this.formData.materials.reduce(
          (sum, item) => sum + (item?.consumeNum || 0),
          0,
        );
        this.footerData[0].consumeCost = this.formData.materials.reduce(
          (sum, item) => sum + (item.consumeCost || 0),
          0,
        );
      },
    },
  });
</script>
